﻿using ALProtocol.Tcp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Demo
{
    /// <summary>
    /// TCP的服务端测试。
    /// </summary>
    internal class TcpServerDemo
    {
        /// <summary>
        /// 服务端的实例。
        /// </summary>
        private readonly TcpServer m_server;
        private readonly List<DemoSession> m_clientList = new List<DemoSession>();
        /// <summary>
        /// 
        /// </summary>
        public TcpServerDemo()
        {
            m_server = new TcpServer();
            m_server.SessionChanged += OnSessionChanged;
        }

        /// <summary>
        /// 启动。
        /// </summary>
        /// <param name="address"></param>
        /// <param name="port"></param>
        /// <returns></returns>
        public bool Start(IPAddress address, int port)
        {
            return m_server.Bind(new IPEndPoint(address, port));
        }
        private void OnSessionChanged(TcpSession session, bool connected)
        {
            lock (m_clientList)
            {
                if (connected)
                {
                    Console.WriteLine($"链接会话（端口：{session.Remote.Port}）");
                    m_clientList.Add(new DemoSession(session, true));
                }
                else
                {
                    Console.WriteLine($"断开会话（端口：{session.Remote.Port}）");
                    var ss = m_clientList.FirstOrDefault(x => x.m_session == session);
                    if (ss != null)
                    {
                        m_clientList.Remove(ss);
                    }
                }
            }
        }
    }
}
